package com.open.capacity.user.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysDict;
import com.open.capacity.user.model.SysDictData;
import com.open.capacity.user.service.SysDictDataService;
import com.open.capacity.user.service.SysDictService;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.list.TreeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 字典管理
 */
@RestController
@Api(tags = "字典模块api")
public class SysDictDataController {

    private static Logger logger = LoggerFactory.getLogger(SysDictDataController.class);


    @Autowired
    private SysDictService dictService;

    @Autowired
    private SysDictDataService dictDataService;


    /**
     * 查询字典数据list
     *
     * @param code
     * @param keyword
     * @return
     */
    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "查询字典数据list")
    @GetMapping("/dictDatas/list")
    public Result<List<SysDictData>> listDictDatas(@RequestParam(value = "code") String code, @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("keyword", keyword);
        List<SysDictData> dicts = dictDataService.findDictDatas(params);
        return Result.succeed(dicts);
    }

    /**
     * 查询字典数据tree
     *
     * @param code
     * @param keyword
     * @return
     */
    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "查询字典数据")
    @GetMapping("/dictDatas/tree")
    public Result<List<TreeVo>> treeDictDatas(@RequestParam(value = "code") String code, @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("status", 1);
        params.put("keyword", keyword);
        List<SysDictData> dicts = dictDataService.findDictDatas(params);
        List<TreeVo> treeList = new TreeList();
        dicts.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getValue());
            node.setText(m.getName());
            node.setValue(m.getName());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(true);
            node.setHasChildren(false);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });
        return Result.succeed(treeList);
    }



    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "判断字典数据name是否存在")
    @GetMapping("/dictDatas/existsName")
    public Result existsName(@RequestParam(value = "code") String code, @RequestParam(value = "name") String name) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("name", name);
        List<SysDictData> list = dictDataService.findDictDatas(params);
        return Result.succeed(CollectionUtils.isNotEmpty(list));
    }

    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "判断字典name是否存在")
    @GetMapping("/dictDatas/existsValue")
    public Result existsValue(@RequestParam(value = "code") String code, @RequestParam(value = "value") String value) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("value", value);
        List<SysDictData> list = dictDataService.findDictDatas(params);
        return Result.succeed(CollectionUtils.isNotEmpty(list));
    }


    /**
     * 字典数据新增或者更新
     *
     * @param sysDictData
     * @return
     */
    @PreAuthorize("hasAnyAuthority('dict:post/dicts','dict:put/dicts')")
    @ApiOperation(value = "保存字典")
    @PostMapping("/dictDatas/saveOrUpdate")
    @LogAnnotation(module = "字典", name = "更新")
    public Result saveOrUpdate(@RequestBody SysDictData sysDictData, String keyValue, String code) {
        sysDictData.setCode(code);
        SysDict dict = dictService.findByCode(code);
        if (dict != null) {
            sysDictData.setDictId(dict.getId());
        }
        return dictDataService.saveOrUpdate(sysDictData, keyValue);
    }

    /**
     * 删除字典
     * delete /dictDatas/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('dict:delete/dicts/{id}')")
    @ApiOperation(value = "删除字典")
    @DeleteMapping("/dictDatas/{id}")
    @LogAnnotation(module = "字典", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            dictDataService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }
}
